<template>
  <main
    class="w-full min-h-screen bg-gradient-to-br from-indigo-500 via-blue-4 00 to-purple-200 overflow-x-hidden relative">
    <div ref="box" class="box1"></div>
    <button @click="animate">Animate</button>
    <div class="container">
      <div v-for="(item, i) in 10" :key="i" ref="box2" class="box2">
        Box {{ i + 1 }}
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
const { $gsap } = useNuxtApp()

import { onUpdated, getCurrentInstance } from 'vue'
const boxes = ref<HTMLElement[]>([])
const box = ref<HTMLElement | null>(null)

const animate = () => {
  if (box.value) {
    $gsap.to(box.value, {
      x: 800,
      rotation: 360,
      duration: 2,
      ease: 'bounce.in'
    })
  }
  setTimeout(() => {
    animateInit1()
  }, 3000);
}

const animateInit1 = () => {
  if (box.value) {
    $gsap.from(box.value, {
      opacity: 0,
      y: 50,
      duration: 1
    })
  }
}
const animateInit2 = () => {
  // @ts-ignore
  const boxElements = (getCurrentInstance()?.proxy?.$refs.box2 as HTMLElement[]) || []
  boxElements.forEach((box, i) => {
    $gsap.from(box, {
      scrollTrigger: {
        trigger: box,
        start: 'top 80%',
        toggleActions: 'play none none none'
      },
      x: i % 2 === 0 ? -100 : 100,
      opacity: 0,
      duration: 1
    })
  })
}

// 生命周期中使用
onMounted(() => {
  animateInit1()
  animateInit2()
})
</script>

<style scoped>
.box1 {
  width: 100px;
  height: 100px;
  background-color: #42b983;
  margin: 20px;
}

.container {
  height: 200vh;
  padding: 50px;
}

.box2 {
  width: 200px;
  height: 200px;
  background-color: #42b983;
  margin: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 24px;
}
</style>